<template>
  <el-upload
    ref="upload"
    class="upload"
    :limit="1"
    :auto-upload="true"
    list-type="picture"
    :show-file-list="false" action="#"
    :before-upload="beforeUpload"
    :http-request="httpRequest"
    v-bind="$attrs"
    v-on="$listeners"
  >
    <template v-if="imgUrl">
      <img class="upload-image" :src="imgUrl" alt="imgUrl">
      <svg-icon name="close" class="remove-icon" @click.stop="remove"></svg-icon>
    </template>
    <svg-icon v-else name="add" class="upload-icon"></svg-icon>
  </el-upload>
</template>

<script>
import { upload, remove } from '@/api/minio'

const api = { upload, remove }
export default {
  name: 'custom-upload',
  inheritAttrs: false,
  props: {
    url: String,
    name: String
  },
  data () {
    return {
      imgUrl: this.url,
      imgName: this.name
    }
  },
  watch: {
    url (val) {
      this.imgUrl = val
    },
    name (val) {
      this.imgName = val
    }
  },
  methods: {
    remove () {
      return api.remove(this.imgName).then(res => {
        if (res.code === 200) {
          this.$refs.upload.clearFiles()
          this.$message.success('删除文件成功')
          this.imgUrl = ''
          this.imgName = ''
          this.$emit('remove')
        }
      })
    },
    beforeUpload (file) {
      const isImage = file.type.indexOf('image') > -1
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isImage) {
        this.$message.error('上传文件格式不对')
      }
      if (!isLt10M) {
        this.$message.error('上传文件大小不能超过10M')
      }
      return isImage && isLt10M
    },
    httpRequest ({ file }) {
      api.upload(file).then(res => {
        if (res.code === 200) {
          this.imgUrl = res.data.url
          this.imgName = res.data.urlName
          this.$emit('upload', res.data)
        }
      })
    },
    clearFiles () {
      this.$refs.upload.clearFiles()
    },
  }
}
</script>

<style lang="scss" scoped>
  .upload {
    ::v-deep .el-upload {
      width: 50px;
      height: 50px;
      border: 1px solid #ddd;
      border-radius: 3px;
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;
    }
  }
  .remove-icon {
    position: absolute;
    right: 0;
    top: 0;
    transform: translate(50%, -50%);
    background: #f5f5f5;
    font-size: 11px;
    color: var(--danger-color);
  }
  .upload-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  .upload-icon {
    font-size: 20px;
  }
</style>
